//
//  PopoverAnimationManager.swift
//  WBDemo
//
//  Created by Jin on 18/04/2018.
//  Copyright © 2018 com.baidu.123. All rights reserved.
//

import UIKit

class PopoverAnimationManager: UIPresentationController,UIViewControllerTransitioningDelegate,UIViewControllerAnimatedTransitioning {
    
    private var isPresent = false
    var presentedFrame = CGRect.zero
    
    func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController?{
        let pc = JLPresentationController(presentedViewController: presented, presenting: presenting)
        pc.presentedFrame = presentedFrame
        return pc
    }
    
    func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresent = true
        NotificationCenter.default.post(Notification(name: Notification.Name(rawValue: JLPopoverViewControllerShowClick)))
        return self as UIViewControllerAnimatedTransitioning
    }
    
    func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresent = false
        NotificationCenter.default.post(Notification(name: Notification.Name(rawValue: JLPopoverViewControllerDismissClick)))
        return self as UIViewControllerAnimatedTransitioning
    }
    
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 0.5
    }
    
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        
        if isPresent {
            let toView = transitionContext.view(forKey: .to)
            transitionContext.containerView.addSubview(toView!)
            
            toView?.transform = CGAffineTransform(scaleX: 1.0, y: 0.0)
            toView?.layer.anchorPoint = CGPoint(x: 0.5, y: 0.0)
            UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {
                toView?.transform = CGAffineTransform.identity
            }) { (_) in
                transitionContext.completeTransition(true)
            }
        }else{
            let fromView = transitionContext.view(forKey: .from)
            UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {
                fromView?.transform = CGAffineTransform(scaleX: 1.0, y: 0.001)
            }) { (_) in
                transitionContext.completeTransition(true)
            }
        }
    }
    
    
}
